package com.dcivision.framework.taglib.channel;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.jsp.JspException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.RootRetrievalManager;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.dms.taglib.LocationPathTag;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.PermissionManager;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;

public class AjaxDmsLocationPathTag extends LocationPathTag {
  
  private Log log = LogFactory.getLog(this.getClass());
  AjaxWriter out = null;
  
  public String getAjaxContent() throws ApplicationException{
    try{
      out = (AjaxWriter)pageContext.getOut();
      out.clear();
      this.doStartTag();
      this.doEndTag();
      return out.getContent().toString();
    }catch(IOException ex){
      log.error(ex.getMessage(), ex);
      throw new ApplicationException(ex);
    }catch(JspException ex){
      log.error(ex.getMessage(), ex);
      throw new ApplicationException(ex);
    }
  }
  
  protected String src() throws javax.servlet.jsp.JspException {

    //limitLength = getDefaultValue();
    this.setLimitLength(getDefaultValue());
    //FormTag formTag = (FormTag)BodyTagSupport.findAncestorWithClass(this, FormTag.class);

    SessionContainer sessionContainer = (SessionContainer)this.pageContext.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    Connection conn = (Connection)pageContext.getRequest().getAttribute(GlobalConstant.DB_KEY);
    String contextPath = (String)this.pageContext.getServletContext().getAttribute(GlobalConstant.CONTEXT_PATH_KEY);
    DmsDocumentDAObject dmsDocmentDAO = new DmsDocumentDAObject(sessionContainer, conn);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    RootRetrievalManager rootRetrievalManager = new RootRetrievalManager(sessionContainer, conn);
    PermissionManager permissionManager = sessionContainer.getPermissionManager();

    StringBuffer buffer = new StringBuffer();
    String path="";
    try {
      if (this.getShowAllPath()) {
        do {
          DmsDocument doc = docRetrievalManager.getDocument(this.getParentID());
//          DmsDocument documentRoot = docRetrievalManager.getRootFolderByRootID(((DmsDocument) doc).getRootID());
//          String permission = (String) permissionManager.getPermission(GlobalConstant.OBJECT_TYPE_DOCUMENT, documentRoot.getID());

          if (this.getRootDocument()==null) {
            buffer.insert(0, GlobalConstant.EMPTY_FIELD);
            break;
          }
          if (DmsOperationConstant.DMS_PERSONAL_ROOT.equals(this.getRootDocument().getDocumentName())){
            //For Personal Folder
            String name = doc.getDocumentName();
            if (this.getRootDocument().getOwnerID().intValue() != sessionContainer.getUserRecordID().intValue()){
              name = UserInfoFactory.getUserFullName(doc.getOwnerID()) + " " +doc.getDocumentName();
              buffer.insert(0, name);
            }else{
              if (!this.getOnClick()) {
                buffer.insert(0, name);
              } else {
                if (GlobalConstant.RECORD_STATUS_ACTIVE.equals(doc.getRecordStatus())){
                  String url = contextPath + "/dms/ListDmsDocument.do?rootID=" + this.getRootID() + "&parentID=" + this.getParentID() +  "&curFunctionCode=" + SystemFunctionConstant.DMS_PERSONAL_FOLDER + "&sortAttribute=";
                  buffer.insert(0, " <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\"/>" + name + "</a>");
                }
                else {
                  buffer.insert(0, name);
                }
              }
            }
          } else {
            //For Public Folder
            if  (this.getPermission().indexOf("R")>=0) {
              if (!this.getOnClick()) {
                buffer.insert(0, doc.getDocumentName());
              } else {
                if (GlobalConstant.RECORD_STATUS_ACTIVE.equals(doc.getRecordStatus())) {
                  String url = contextPath + "/dms/ListDmsPublicDocument.do?rootID=" + this.getRootID() + "&parentID=" + this.getParentID() +  "&curFunctionCode=" + SystemFunctionConstant.DMS_PUBLIC_FOLDER +"&sortAttribute=";
                  buffer.insert(0, " <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\"/>" + doc.getDocumentName() + "</a>");
                } else {
                  buffer.insert(0, doc.getDocumentName());
                }
              }
            } else {
              buffer.insert(0, doc.getDocumentName());
            }
          }
          buffer.insert(0, FILE_SEPARATOR);
          this.setParentID(doc.getParentID());
        } while (this.getParentID().intValue()!=0);

        path = buffer.toString();
        if (path.length() > 0) {
          path = path.substring(1);
        }
      } else {
        DmsDocument doc = docRetrievalManager.getDocument(this.getParentID());
        String name = docRetrievalManager.getLocationPath(this.getParentID());

        if (name.length() > this.getLimitLength()) {
          name = name.substring(0,this.getLimitLength()).replaceAll(" ", "&nbsp;")+"...";
        }

        if (this.getRootDocument() != null && DmsOperationConstant.DMS_PERSONAL_ROOT.equals(this.getRootDocument().getDocumentName())) {
          //For Personal Folder
          if (this.getRootDocument().getOwnerID().intValue() != sessionContainer.getUserRecordID().intValue()) {
            if(docRetrievalManager.getLocationPath(this.getParentID()).length() > this.getLimitLength() ) {
              name = docRetrievalManager.getLocationPath(this.getParentID()).substring(0,this.getLimitLength()).replaceAll(" ", "&nbsp;")+"...";
            }
            buffer.insert(0, name);
          } else {
            if (!this.getOnClick()) {
            buffer.insert(0, name);
            } else {
              if (GlobalConstant.RECORD_STATUS_ACTIVE.equals(doc.getRecordStatus())) {
                String url = contextPath + "/dms/ListDmsDocument.do?rootID=" + this.getRootID() + "&parentID=" + this.getParentID() +  "&curFunctionCode=" + SystemFunctionConstant.DMS_PERSONAL_FOLDER + "&sortAttribute=";
                if (this.getShowIndexFlag()) {
                  buffer.insert(0, " <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\" " +
                    " onmouseover=\" return getDocumentInfo('" +TextUtility.escapeJSString(docRetrievalManager.getLocationPath(this.getParentID())) + "'); \" onmouseout=\"return nd();\">" + name + "</a>");
                } else {
                  buffer.insert(0, "  <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\" "+
                    " onmouseover=\"return(false);\">" + name + "</font></a>");
                }
              } else {
                buffer.insert(0, name);
              }
            }
          }
        } else {
          //For Public Folder
          if  (this.getPermission().indexOf("R")>=0) {
            if (!this.getOnClick()) {
              buffer.insert(0, name);
            } else {
              if (GlobalConstant.RECORD_STATUS_ACTIVE.equals(doc.getRecordStatus())) {
                String url ="";
                if("showSystemLogIndexFlag".equals(this.getIndexFlag())||"showRecentlyAccessIndexFlag".equals(this.getIndexFlag())){
                  url = contextPath + "/dms/ListDmsPublicDocument.do?rootID=" + this.getRootID() + "&parentID=" + this.getParentID() +  "&curFunctionCode=" + DmsOperationConstant.LIST_PERSONAL_HOME +"&sortAttribute="; 
                }else{
                  url = contextPath + "/dms/ListDmsPublicDocument.do?rootID=" + this.getRootID() + "&parentID=" + this.getParentID() +  "&curFunctionCode=" + SystemFunctionConstant.DMS_PUBLIC_FOLDER +"&sortAttribute=";
                }
                if (this.getShowIndexFlag()) {
                   buffer.insert(0, " <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\" " +
                     " onmouseover=\" return getDocumentInfo('" +TextUtility.escapeJSString(docRetrievalManager.getLocationPath(this.getParentID())) + "'); \" onmouseout=\"return nd();\">" + name + "</a>");
                } else {
                   buffer.insert(0, "  <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\" "+
                     " onmouseover=\"return(false);\">" + name + "</font></a>");
                }
                //buffer.insert(0, " <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\"/>" + name + "</a>");
              } else {
                buffer.insert(0, name);
              }
            }
          } else {
            buffer.insert(0, name);
          }
        }
        buffer.insert(0, FILE_SEPARATOR);

        path = buffer.toString();
        if (path.length() > 0) {
          path = path.substring(1);
        }
        String url = contextPath + "/dms/ListDmsDocument.do?rootID=" + this.getRootID() + "&parentID=" + this.getParentID() +  "&curFunctionCode=" + SystemFunctionConstant.DMS_PERSONAL_FOLDER + "&sortAttribute=";
        if (path.indexOf("<a href")<0 && path.length() > this.getLimitLength()) {
           path = " <a href=\"javascript://\" onmouseover=\" return getDocumentInfo('" +TextUtility.escapeJSString(docRetrievalManager.getLocationPath(this.getParentID())) + "'); \" onmouseout=\"return nd();\">" + path.substring(0,this.getLimitLength()).replaceAll(" ", "&nbsp;")+"..." + "</a>";
        }
      }
    } catch (ApplicationException appEx) {
      throw new JspException(appEx);
    }

    return path;
  }
}
